//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    msgData: {
      mobile: '',
      vcode: '',
      zcode: 86
    },
    disabled: true,
    loading: false,
    disabledCode: false,
    time: '',
    zcodes: [],
    index: 0
  },
  changeInput(e) {
    this.data.msgData[e.target.id] = e.detail.value
    if (this.data.msgData.mobile.length >0 && this.data.msgData.vcode.length > 0) {
      this.data.disabled = false
    } else {
      this.data.disabled = true
    }
    this.setData({
      msgData: this.data.msgData,
      disabled: this.data.disabled
    })
  },
  bindPickerChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.data.msgData.zcode = this.data.zcodes[e.detail.value].zcode
    this.setData({
      index: e.detail.value,
      msgData: this.data.msgData
    })
  },
  getCode() {
    // 获取验证码
    if (this.data.disabledCode) return
    this.setData({
      disabledCode: true
    })
    app.$http('/vcode', {
      mobile: this.data.msgData.mobile,
      zcode: this.data.msgData.zcode
    }).then(response => {
      wx.showToast({
        title: '短信发送成功',
        icon: 'success',
        duration: 3000
      })
      let time = 60
      let codeInterval = setInterval(_ => {
        if (time <= 0) {
          clearInterval(codeInterval)
          this.setData({
            disabledCode: false,
            time: ''
          })
        } else {
          time = time - 1
          this.setData({
            time: '(' + time + 's)'
          })
        }
      }, 1000)
    }, error => {
      this.setData({
        disabledCode: false
      })
    })
  },
  addMembder() {
    wx.showLoading({
      title: '绑定中...',
      mask: true
    })
    app.$http('/bind', this.data.msgData, 'put').then(response => {
      app.getUserInfo()
      wx.navigateBack({
        delta: 1
      })
    }, error => {})
  },
  onShow() {
    app.$http('/zcodes').then(response => {
      this.setData({
        zcodes: response
      })
    }, error => {})
  }
})
